package pay

import (
	"OnlineRetailers/models"
	USER "OnlineRetailers/models/User"
	"encoding/json"
	"github.com/garyburd/redigo/redis"
)

func Destroy(orderId string) (err error) {

	conn := models.Pool.Get()

	defer func() {
		err = conn.Close()
		if err != nil {

		}
	}()

	_, err = conn.Do("DEL", orderId)
	return

}

func Update(orderId string) (err error) {

	conn := models.Pool.Get()

	defer func() {
		err = conn.Close()
		if err != nil {

		}
	}()

	_, err = conn.Do("EXPIRE", orderId, 10*models.Minutes)

	return

}

func New(orderId string, order *USER.Order) (err error) {

	orderJson, err := json.Marshal(order)
	if err != nil {
		return
	}

	conn := models.Pool.Get()

	defer func() {
		err = conn.Close()
		if err != nil {
			return
		}
	}()

	_, err = conn.Do("SET", orderId, orderJson)
	if err != nil {
		return
	}
	err = Update(orderId)

	return

}

func Find(orderId string) (order *USER.Order, err error) {

	conn := models.Pool.Get()

	defer func() {
		err = conn.Close()
		if err != nil {

		}
	}()

	sessionJson, err := redis.Bytes(conn.Do("Get", orderId))
	if err != nil {
		return
	}
	err = json.Unmarshal(sessionJson, &order)
	if err != nil {
		return
	}

	return
}
